import React, { JSX } from "react";
import { NulCommonOperations, NulDialog, NulFormItem } from "../../components/NulDialog";
import { Autocomplete, TextField, Typography } from "@mui/material";
import { InventoryEntry } from "../../actions/InventoryManagement";
import { AlertBox } from "../../components/AlertBox";
import { useAppDispatch } from "../../actions/hook";
import { addIssueInvoice } from "../../actions/IssueInvoice";

interface CreateInvoiceEntryDialogProps {
  open: boolean;
  onClose: () => void;
  inventoryEntries: InventoryEntry[];
  warehouseId: number;
};

function CreateInvoiceEntryDialog(props: CreateInvoiceEntryDialogProps): JSX.Element {
  const { open, onClose, inventoryEntries } = props;

  const [inventory, setInventory] = React.useState<InventoryEntry | null>(null);
  const [quantity, setQuantity] = React.useState<string>('');
  const [openErrorAlert, setOpenErrorAlert] = React.useState<boolean>(false);

  const dispatch = useAppDispatch();

  const handlePositiveClicked = () => {
    const quantityNumber: number = parseInt(quantity);
    if (inventory === null || isNaN(quantityNumber) || quantityNumber > inventory.quantity) {
      setOpenErrorAlert(true);
    }
    else {
      dispatch(addIssueInvoice({
        id: inventory.id,
        wholesalePrice: inventory.wholesalePrice,
        costPrice: inventory.costPrice,
        retailPrice: inventory.retailPrice,
        name: inventory.name,
        quantity
      }));
      onClose();
    }
  };

  return (
    <>
      <NulDialog
        open={open}
        onClose={onClose}
        title='Create Invoice Entry'
        operations={
          <NulCommonOperations
            onNegativeClicked={onClose}
            onPositiveClicked={handlePositiveClicked}
            positiveText='Create'
          />
        }
      >
        <NulFormItem hint='Inventory' component={
          <Autocomplete
            options={inventoryEntries}
            getOptionLabel={(value) => value.name}
            value={inventory}
            onChange={(action, value) => { setInventory(value); }}
            renderInput={(params) => <TextField {...params} />}
            size='small'
            fullWidth
          />
        } />
        <NulFormItem hint='Cost Price' necessary={false} component={
          <Typography>
            {inventory === null ? 0 : inventory.costPrice}
          </Typography>
        } />
        <NulFormItem hint='Quantity' component={
          <TextField value={quantity} onChange={(action) => { setQuantity(action.target.value); }} size='small' fullWidth={true} />
        } />
      </NulDialog>
      <AlertBox
        open={openErrorAlert}
        onClose={() => { setOpenErrorAlert(false); }}
        title='Error'
        message='Invalid quantity or inventory.'
        autoHideDuration={4000}
        severity='warning'
      />
    </>
  );
}

export default CreateInvoiceEntryDialog;